package com.zhoux.springbucks.service;

import com.zhoux.springbucks.mapper.CoffeeMapper;
import com.zhoux.springbucks.model.Coffee;
import com.zhoux.springbucks.repository.CoffeeRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.exact;

@Slf4j
@Service
public class CoffeeService {
    @Autowired
    private CoffeeRepository coffeeRepository;
    @Autowired
    private CoffeeMapper coffeeMapper;

    /**
     * 插叙单条coffee
     * @param id
     * @return
     */
    public Optional<Coffee> findOneCoffee(long id) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("id", exact().ignoreCase());
        Optional<Coffee> coffee = coffeeRepository.findOne(
                Example.of(Coffee.builder().id(id).build(), matcher));
        log.info("Coffee Found: {}", coffee);
        return coffee;
    }

    /**
     * 插叙所有coffee
     * @return
     */
    public List<Coffee> findAllCoffee() {
        List<Coffee> coffeeList = coffeeRepository.findAll();
        log.info("coffeeList Found: {}", coffeeList);
        return coffeeList;
    }

    @Transactional
    public void creatOneCoffee(Coffee coffee) {
        log.info("Coffee Add: {}", coffee);
        coffeeRepository.saveAndFlush(coffee);
        log.info("Add success");
    }

    @Transactional
    public void updateOneCoffee(Coffee coffee) {
        log.info("Coffee update: {}", coffee);
        coffeeRepository.save(coffee);
        log.info("update success");
    }

    @Transactional
    public void delOneCoffee(long id) {
        log.info("Coffee delete: {}", id);
        coffeeRepository.deleteById(id);
        log.info("delete success");
    }
}
